import { Switch } from '@/components/ui/switch'
import { Link } from 'react-router-dom'
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger
} from '@/components/ui/tooltip'
import { TooltipProvider } from '@/components/ui/tooltip'
import { Battle } from '@/types/battle'
import React from 'react'
import { battleSave } from '@/apis/battle'
import { IpViewer } from './ip'

interface BattleRowProps {
  battle: Battle
  selfIp: number | null
}

export function BattleRow({ battle, selfIp }: BattleRowProps) {
  const isSelf =
    selfIp !== null && battle.created_ip === selfIp && battle.created_ip !== 0

  const pathname = window.location.pathname
  const showAlias = pathname.endsWith('/sun2') || pathname.endsWith('/hshe')
  const showIp = pathname.endsWith('/hshe')

  const [status, setStatus] = React.useState(battle.status)

  const handleSwitch = async (checked: boolean) => {
    const newStatus = checked ? 1 : 2
    setStatus(newStatus)
    await battleSave({
      data: {
        id: battle.id,
        title: battle.title || '',
        path: battle.path,
        status: newStatus
      }
    })
  }

  // 改淡按钮颜色（去掉边框）
  const switchColor = status === 1 ? 'bg-green-300' : 'bg-gray-200'

  const containerBase =
    'flex flex-col gap-1 border border-gray-50 bg-gradient-to-br px-4 py-2 shadow-lg transition-all duration-300 dark:border-gray-800 group'
  const containerSelf =
    'from-green-50 to-green-100 hover:from-green-100 hover:to-green-200 dark:from-green-900 dark:to-green-800 dark:hover:from-green-800 dark:hover:to-green-700'
  const containerOther =
    'from-white to-gray-50 hover:from-gray-100 hover:to-gray-200 dark:from-gray-900 dark:to-gray-800 dark:hover:from-gray-800 dark:hover:to-gray-700'
  const containerClass = `${containerBase} ${
    isSelf ? containerSelf : containerOther
  }`

  const linkBase = 'shrink truncate drop-shadow-sm hover:underline'
  const linkSelf = 'text-green-700 dark:text-green-300 max-w-[50%]'
  const linkOther = 'w-full text-gray-900 dark:text-white max-w-full'
  const linkClass = `${linkBase} ${isSelf ? linkSelf : linkOther}`

  const linkMobileSelf =
    'shrink text-green-700 drop-shadow-sm hover:underline dark:text-green-300 max-w-3/5'
  const linkMobileOther =
    'w-full shrink text-gray-900 drop-shadow-sm hover:underline dark:text-white max-w-full'
  const linkMobileClass = `${
    isSelf ? linkMobileSelf : linkMobileOther
  } truncate`

  const timeSelf = 'text-xs text-green-700 opacity-80 dark:text-green-300'
  const timeOther = 'text-xs text-gray-500 opacity-80 dark:text-gray-400'
  const timeClass = `overflow-visible text-clip whitespace-nowrap font-mono font-tabular-nums ${
    isSelf ? timeSelf : timeOther
  }`

  const mobileRowClass = `mt-1 flex w-full items-center md:hidden ${
    isSelf
      ? 'text-green-700 dark:text-green-300'
      : 'text-gray-500 dark:text-gray-400'
  }`

  return (
    <TooltipProvider>
      <div className={containerClass}>
        <div className="flex w-full flex-col">
          {/* PC端 */}
          <div className="hidden w-full flex-nowrap items-center md:flex">
            <Link
              to={`./${battle.id}`}
              className={linkClass}
              style={{ maxWidth: isSelf ? '50%' : '100%' }}
            >
              <span className="mr-1 text-xs text-gray-400 dark:text-gray-500">
                {battle.id}
                {showAlias && battle.alias ? ` (${battle.alias})` : ''}
              </span>
              {battle.title}
            </Link>
            <div className="flex-1" />
            <div className="flex items-center gap-2">
              {/* 按钮 */}
              {isSelf && (
                <Tooltip>
                  <TooltipTrigger asChild>
                    <Switch
                      className={`scale-90 cursor-pointer shadow-sm transition-all ${switchColor} h-4 w-8`}
                      checked={status == 1}
                      onCheckedChange={handleSwitch}
                    />
                  </TooltipTrigger>
                  <TooltipContent side="top" align="center">
                    {status == 1 ? '当前：公开展示' : '当前：仅自己可见'}
                  </TooltipContent>
                </Tooltip>
              )}
              {/* 时间 */}
              <span className={timeClass}>
                {new Date(battle.created_at).toLocaleString('zh-CN')}
              </span>
              {/* IP */}
              {showIp && <IpViewer ip={battle.created_ip} />}
            </div>
          </div>

          {/* 手机端 */}
          <div className={mobileRowClass}>
            <Link
              to={`./${battle.id}`}
              className={linkMobileClass}
              style={{ maxWidth: isSelf ? '60%' : '100%' }}
            >
              <span className="mr-1 text-xs text-gray-400 dark:text-gray-500">
                {battle.id}
                {showAlias && battle.alias ? `(${battle.alias})` : ''}
              </span>
              {battle.title}
            </Link>
            <div className="flex-1" />
            {/* 按钮 */}
            {isSelf && (
              <Tooltip>
                <TooltipTrigger asChild>
                  <Switch
                    className={`scale-90 cursor-pointer shadow-sm transition-all ${switchColor} h-4 w-8`}
                    checked={status == 1}
                    onCheckedChange={handleSwitch}
                  />
                </TooltipTrigger>
                <TooltipContent side="top" align="center">
                  {status == 1 ? '当前：公开展示' : '当前：仅自己可见'}
                </TooltipContent>
              </Tooltip>
            )}
            {/* 时间 */}
            <span className="ml-2 max-w-[120px] overflow-visible text-clip whitespace-nowrap font-mono text-xs opacity-80">
              {new Date(battle.created_at).toLocaleString('zh-CN')}
            </span>
            {/* IP */}
            {showIp && <IpViewer ip={battle.created_ip} />}
          </div>
        </div>
      </div>
    </TooltipProvider>
  )
}
